package org.example.mq.mqserver.core;

import jakarta.annotation.PostConstruct;
import org.example.mq.common.*;
import org.example.mq.common.arguments.*;
import org.example.mq.common.exception.MqException;
import org.example.mq.common.tools.BinaryTool;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class BrokerServer {
    // 默认端口，RabbitMQ
    private int port = 5672;

    @Autowired
    private ObjectFactory<VirtualHost> virtualHostFactory;
    // 存储所有 VirtualHost
    private Map<String, VirtualHost> virtualHosts = new ConcurrentHashMap<>();
    //管理socket连接 <channelId,clientSocket>
    private ConcurrentHashMap<String,Socket> sessions = new ConcurrentHashMap<>();
    //引入线程池来处理客户端连接
    private ExecutorService executorService = null;
    //控制服务器是否运行
    private volatile boolean runnable = true;
    //服务器socket
    private ServerSocket serverSocket = null;
    private final Object writeLock = new Object();
    public VirtualHost createVirtualHost(String hostName) {
        VirtualHost vh = virtualHostFactory.getObject();
        vh.setHostName(hostName);
        virtualHosts.put(hostName, vh);
        return vh;
    }

    @PostConstruct
    public void init() throws SocketException {
        Thread thread = new Thread(()->{
            try {
                start();
            } catch (SocketException e) {
                throw new RuntimeException(e);
            }
        });
        thread.start();
    }

    public VirtualHost getVirtualHost(String hostName) {
        return virtualHosts.get(hostName);
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void start() throws SocketException {
        try{
            serverSocket = new ServerSocket(port);

            System.out.println("BrokerServer 启动成功，监听端口: " + port);
            executorService = Executors.newCachedThreadPool();

            while(runnable){
                Socket clientSocket = serverSocket.accept();
                System.out.println("收到客户端连接: " + clientSocket.getInetAddress().toString());

                //将连接的处理逻辑丢给线程池
                executorService.submit(()->{
                    processConnection(clientSocket);
                });
            }
        }catch (SocketException e) {
            // 这是 stop() 时 serverSocket.close() 触发的，不算异常
            if (!runnable) {
                System.out.println("BrokerServer 停止监听端口");
            } else {
                throw e;
            }
        }
        catch (IOException e) {
            System.out.println("BrokerServer 启动失败！");
            throw new RuntimeException(e);
        }
    }

    //停止服务
    public void stop() throws IOException {
        runnable = false;
        executorService.shutdownNow();
        serverSocket.close();
        virtualHosts.clear();
        sessions.clear();
    }

    private void processConnection(Socket clientSocket){
        try(
                DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream());
                DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream())
        ){
            while(!clientSocket.isClosed()) {
                //1.解析请求
                Request request = readRequest(dataInputStream);
                System.out.println("[BrokerServer]processConnection接收到request:"+request.getType());
                //2.处理响应
                Response response = process(request, clientSocket);
                //3.写回响应
                writeResponse(dataOutputStream, response);
            }
        }catch (EOFException | SocketException exception){
            //客户端连接关闭
            System.out.println("客户端连接已被关闭！客户端地址为："+clientSocket.getInetAddress().toString());
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //这里只有读到eof（客户端主动关闭连接才会读到），相当于客户端断开连接
            //关闭连接,无论是异常关闭还是正常关闭，都要关闭socket连接
            try {
                clientSocket.close();
                //一个 connection 中包含多个 channel 需要把 channel 全部关闭
                clearCloseSocket(clientSocket);
            } catch (IOException e) {
                throw new MqException("[BrokerServer:processConnection]关闭连接异常！");
            }
        }
    }

    private void clearCloseSocket(Socket clientSocket) {
        List<String>channelIds = new ArrayList<>();

        for (Map.Entry<String,Socket>session : sessions.entrySet()){
            if(session.getValue()==clientSocket){
                //不能在此处直接删除，因为集合类使用大忌一边遍历一边删除
                channelIds.add(session.getKey());
            }
        }

        for (String channelId : channelIds) {
            sessions.remove(channelId);
        }
    }

    private Response process(Request request,Socket clientSocket) {
        //参数反序列化
        BasicArguments basicArguments = (BasicArguments) BinaryTool.toObject(request.getPayload());

        boolean ok = false;
        int type = request.getType();

        /*
         * 根据 type 不同取值来判断功能
         * 0x1 创建channel
         * 0x2 关闭channel
         * 0x3 创建交换机
         * 0x4 删除交换机
         * 0x5 创建队列
         * 0x6 删除队列
         * 0x7 绑定
         * 0x8 交换机取消绑定
         * 0x9 队列&&交换机取消指定绑定
         * 0xa 发送消息到交换机
         * 0xb basicConsume
         * 0xc basicAck
         * 0xd return
         */
        //根据参数中的VirtualHostName去拿到VirtualHost实例
        VirtualHost virtualHost = virtualHosts.get(basicArguments.getHostName());

        if(type == 0x1){
            sessions.put(basicArguments.getChannelId(),clientSocket);
            System.out.println("[BrokerServer]:创建channel,channelId:"+basicArguments.getChannelId()+",主机地址："+clientSocket.getInetAddress().toString());
            ok = true;
        }
        else if(type == 0x2){
            Socket remove = sessions.remove(basicArguments.getChannelId());
            if(remove!=null){
                ok = true;
                System.out.println("[BrokerServer]销毁channel:id"+basicArguments.getChannelId()+",主机地址："+clientSocket.getInetAddress().toString());
            }
            else {
                ok = false;
//                throw new MqException("[BrokerServer]process:type = 0x2,删除channel失败！");
                System.out.println("[BrokerServer]process:type = 0x2,删除channel失败！channel不存在!");
            }
        }
        else if(type == 0x3){
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;

            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(), arguments.getExchangeType(),
                    arguments.isDurable(),arguments.isAutoDelete(),arguments.getArguments()
            );
        }
        else if(type == 0x4){
            DeleteExchangeArguments arguments = (DeleteExchangeArguments) basicArguments;
            ok = virtualHost.deleteExchange(arguments.getExchangeName());
        }
        else if(type == 0x5){
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;

            ok = virtualHost.queueDeclare(arguments.getQueueName(),arguments.isDurable(),
                    arguments.isExclusive(),arguments.isAutoDelete(),arguments.getArguments());
        }
        else if(type == 0x6){
            DelQueueArguments arguments = (DelQueueArguments) basicArguments;

            ok = virtualHost.delQueue(arguments.getQueueName());
        }
        else if(type == 0x7){
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;

            ok = virtualHost.queueBind(arguments.getExchangeName(), arguments.getQueueName(),arguments.getBindingKey());
        }
        else if(type == 0x8){
            ExchangeUnBindArguments arguments = (ExchangeUnBindArguments) basicArguments;

            ok = virtualHost.exchangeUnBind(arguments.getExchangeName());
        }
        else if(type == 0x9){
            QueueUnBindArguments arguments = (QueueUnBindArguments) basicArguments;

            ok = virtualHost.queueUnBind(arguments.getQueueName(),arguments.getExchangeName());
        }
        else if(type == 0xa){
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;

            ok = virtualHost.basicPublish(arguments.getExchangeName(),arguments.getRoutingKey(),
                    arguments.getBasicProperties(),((BasicPublishArguments) basicArguments).getBody());
        }
        else if(type == 0xb){
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;

            String consumeTag = arguments.getConsumeTag();

            Consumer consumer = new Consumer() {
                @Override
                public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws IOException {
                        /*
                            这里因为客户端并没有实际传回调函数过来
                            服务器自定义一个回调函数，然后交给ConsumerManager线程池执行
                            这函数的内容应该是通过channelId查找到socket 根据这个socket传回消息
                         */
                    System.out.println("[Broker] 进入 handleDelivery, consumerTag=" + consumerTag);

                    //这里要想办法拿到socket对象
                    String queueName = arguments.getHostName()+"_"+ arguments.getQueueName();
                    MessageQueue queue = virtualHost.getMemoryDataCenter().getQueue(queueName);
                    String channelId = queue.getChannelIdByConsumerTag(consumerTag);
                    Socket socket = sessions.get(channelId);

                    System.out.println("[Broker] 准备写回消息给客户端，channelId=" + channelId + ", socket=" + socket);

                    //构造 response 对象
                    Response response = new Response();
                    SubscribeReturns subscribeReturns = new SubscribeReturns();

                    subscribeReturns.setConsumeTag(consumerTag);
                    subscribeReturns.setBasicProperties(basicProperties);
                    subscribeReturns.setBody(body);
                    subscribeReturns.setOk(true);
                    subscribeReturns.setRid(null);
                    subscribeReturns.setChannelId(channelId);

                    byte[] payload = BinaryTool.toBytes(subscribeReturns);

                    response.setType(0xd);
                    response.setLength(payload.length);
                    response.setPayload(payload);

                    //数据写回
                    DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                    writeResponse(dataOutputStream,response);
                    System.out.println("[BrokerServer]消息回调：length"+payload.length);
                }
            };

            if(!StringUtils.hasLength(consumeTag)){
                ok = virtualHost.basicConsume(arguments.getChannelId(), arguments.getQueueName(), arguments.isAutoAck(), consumer);
            }
            else{
                ok = virtualHost.basicConsume(arguments.getChannelId(), consumeTag, arguments.getQueueName(), arguments.isAutoAck(), consumer);
            }
        }else if(type==0xc){
            BasicAckArguments basicAckArguments = (BasicAckArguments) basicArguments;

            ok = virtualHost.basicAck(basicAckArguments.getQueueName(),basicAckArguments.getMessageId());
        }
        else {
            //错误请求类型
            throw new MqException("[BrokerServer]process请求type错误！");
        }

        Response response = new Response();
        BasicReturns basicReturns = new BasicReturns();

        basicReturns.setOk(ok);
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setChannelId(basicArguments.getChannelId());

        byte[] payload = BinaryTool.toBytes(basicReturns);

        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);

        return response;
    }

    private void writeResponse(DataOutputStream dataOutputStream,Response response) throws IOException {
        synchronized (writeLock) {
            dataOutputStream.writeInt(response.getType());
            dataOutputStream.writeInt(response.getLength());
            dataOutputStream.write(response.getPayload());
            dataOutputStream.flush();
        }
    }

    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();

        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());

        byte[] payload = new byte[request.getLength()];
        dataInputStream.read(payload);

        int readLen = payload.length;

        if(readLen!=request.getLength()){
            throw new MqException("[BrokerServer:readRequest]请求参数格式错误!");
        }
        request.setPayload(payload);
        return request;
    }
}
